package com.kyh.service.sys.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kyh.enume.sys.MenuEnum;
import com.kyh.service.sys.MenuService;
import com.kyh.sys.entity.Button;
import com.kyh.sys.entity.Menu;
import com.kyh.sys.entity.Module;
import com.kyh.sys.mapper.ButtonMapper;
import com.kyh.sys.mapper.ColMapper;
import com.kyh.sys.mapper.MenuMapper;
import com.kyh.sys.mapper.ModuleMapper;
import com.kyh.sys.mapper.RoleButtonMapper;
import com.kyh.sys.mapper.RoleMenuMapper;
import com.kyh.util.CheckUtil;
import com.kyh.vo.BootstrapTableVoJA;
import com.kyh.vo.R;

@Service("menuService")
public class MenuServiceImpl implements MenuService {

	@Autowired
	private ButtonMapper buttonMapper;
	@Autowired
	private ColMapper colMapper;
	@Autowired
	private MenuMapper menuMapper;
	@Autowired
	private ModuleMapper moduleMapper;
	@Autowired
	private RoleButtonMapper roleButtonMapper;
	@Autowired
	private RoleMenuMapper roleMenuMapper;

	@Override
	@Transactional
	public R add(Menu entity) throws Exception {

		String menuName = entity.getMenuName();
		if (!CheckUtil.notNull(menuName)) {
			return R.error("名称不能为空");
		}

		Integer menuSortNo = entity.getMenuSortNo();
		if (!CheckUtil.notNull(menuSortNo)) {
			return R.error("排序序号不能为空");
		}

		String menuSortType = entity.getMenuSortType();
		if (!CheckUtil.notNull(menuSortType)) {
			return R.error("排序方式不能为空");
		}
		
		// 菜单等级
		Integer menuLev;
		
		// 验证模块及父菜单
		Long moduleId = entity.getModuleId();
		Long menuPid = entity.getMenuPid();
		if (moduleId != null) {
			Module module = moduleMapper.get(moduleId);
			if (module == null) {
				return R.error("所属模块不存在");
			}
			menuLev = MenuEnum.Lev.ONE.value;
		} else {
			if (menuPid == null) {
				return R.error("父菜单不能为空");
			}
			Menu fmenu = menuMapper.get(menuPid);
			if (fmenu == null) {
				return R.error("父菜单不存在");
			} else if (fmenu.getMenuLev() != 1) {
				return R.error("该菜单无法添加子菜单");
			}
			menuLev = MenuEnum.Lev.TWO.value;
		}
		
		// 验证表名
		String menuTable = entity.getMenuTable();
		if (menuLev == MenuEnum.Lev.TWO.value) {
			if (menuTable == null || menuTable.length() == 0) {
				return R.error("关联表名不能为空");
			}
		}
		
		// 添加数据
		if (menuMapper.insert(entity) != 1) {
			throw new RuntimeException("失败");
		}
		
		Long menuId = entity.getMenuId();
		
		// 添加按钮
		if (menuLev == MenuEnum.Lev.TWO.value) {
			// 添加按钮-新增
			Button buttonAdd = Button.button(menuId, "新增", "btn-add", "", 1);
			buttonMapper.insert(buttonAdd);
			
			// 添加按钮-编辑
			Button buttonEdit = Button.button(menuId, "编辑", "btn-edit", "", 1);
			buttonMapper.insert(buttonEdit);
			
			// 添加按钮-删除
			Button buttonDeleteFalse = Button.button(menuId, "删除", "btn-delete-false", "", 1);
			buttonMapper.insert(buttonDeleteFalse);
			
			// 添加按钮-彻底删除
			Button buttonDeleteTrue = Button.button(menuId, "彻底删除", "btn-delete-true", "", 1);
			buttonMapper.insert(buttonDeleteTrue);
			
			// 添加按钮-导入
			Button buttonImport = Button.button(menuId, "导入", "btn-import", "", 1);
			buttonMapper.insert(buttonImport);
			
			// 添加按钮-导出
			Button buttonExport = Button.button(menuId, "导出", "btn-export", "", 1);
			buttonMapper.insert(buttonExport);
		}
		
		return R.ok();
	}

	@Override
	public R addCols(Long menuId) throws Exception {
		
		return null;
	}

	@Override
	@Transactional
	public R edit(Menu entity) throws Exception {
		
		Long menuId = entity.getMenuId();
		if (!CheckUtil.notNull(menuId)) {
			return R.error("ID不能为空");
		}
		
		String menuName = entity.getMenuName();
		if (!CheckUtil.notNull(menuName)) {
			return R.error("名称不能为空");
		}
		
		Integer menuSortNo = entity.getMenuSortNo();
		if (!CheckUtil.notNull(menuSortNo)) {
			return R.error("排序序号不能为空");
		}
		
		String menuSortType = entity.getMenuSortType();
		if (!CheckUtil.notNull(menuSortType)) {
			return R.error("排序方式不能为空");
		}
		
		Integer menuLev = entity.getMenuLev();
		
		// 验证表名
		String menuTable = entity.getMenuTable();
		if (menuLev == MenuEnum.Lev.TWO.value) {
			if (menuTable == null || menuTable.length() == 0) {
				return R.error("关联表名不能为空");
			}
		}
		
		// 更新数据
		if (menuMapper.update(entity) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	@Transactional
	public R deleteFalse(Long menuId) throws Exception {
		
		if (menuMapper.deleteFalse(menuId) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	@Transactional
	public R deleteTrue(Long menuId) {
		
		// 验证是否有子菜单，有的话不能删除
//		ConfMenu conf = new ConfMenu();
//		conf.e.setMenuPid(menuId);
		if (new Menu().setMenuPid(menuId).count() > 0) {
			return R.error("还有子菜单，不能删除");
		}
		
		// 删除字段
		colMapper.deleteTrueByMenuId(menuId);
		
		// 删除角色按钮
		roleButtonMapper.deleteTrueByMenuId(menuId);
		
		// 删除按钮
		buttonMapper.deleteTrueByMenuId(menuId);
		
		// 删除角色-菜单
		roleMenuMapper.deleteTrueByMenuId(menuId);
		
		menuMapper.deleteTrue(menuId);
		
		return R.ok();
	}

	@Override
	public BootstrapTableVoJA search(Menu cond) {
		
		List<Map<String, Object>> listMap = cond.queryMap();
		
		int total = cond.count();
		
        BootstrapTableVoJA vo = new BootstrapTableVoJA();
        vo.setRowsByListMap(listMap);
        vo.setTotal(total);
        
        return vo;
	}

	@Override
	public R tree() {

		JSONArray JAModule = new JSONArray();
//		List<Module> listModule = moduleMapper.search(new ConfModule());
		List<Module> listModule = new Module().queryList();
		
		for (Module module : listModule) {
			
//			ConfMenu conMenuLevOne = new ConfMenu();;
//			conMenuLevOne.orderBy.setOrderby("menu_sort_no");
//			conMenuLevOne.orderBy.setSorttype("asc");
//			conMenuLevOne.e.setMenuPid(0L);
//			conMenuLevOne.e.setModuleId(module.getModuleId());
//			List<Menu> listEntityParent = menuMapper.search(conMenuLevOne);
			List<Menu> listEntityParent = new Menu().setOrderby("A.menu_sort_no asc").setMenuPid(0L).setModuleId(module.getModuleId()).queryList();
        	JSONArray JAMenuLevOne = new JSONArray();
	        for (Menu menuLevOne : listEntityParent) {
				
				JSONObject JOMenuLevOne = menuLevOne.tree();
				
//	    		ConfMenu conMenuLevTwo = new ConfMenu();;
//	    		conMenuLevTwo.orderBy.setOrderby("menu_sort_no");
//	    		conMenuLevTwo.orderBy.setSorttype("asc");
//	    		conMenuLevTwo.e.setMenuPid(menuLevOne.getMenuId());
//				List<Menu> listEntityChild = menuMapper.search(conMenuLevTwo);
				List<Menu> listEntityChild = new Menu().setOrderby("A.menu_sort_no asc").setMenuPid(menuLevOne.getMenuId()).queryList();
	        	JSONArray JAMenuLevTwo = new JSONArray();
				for (Menu menuLevTwo : listEntityChild) {
	    			JSONObject JOMenuLevTwo = menuLevTwo.tree();
	    			JAMenuLevTwo.add(JOMenuLevTwo);
				}
				JOMenuLevOne.put("nodes", JAMenuLevTwo);
				JAMenuLevOne.add(JOMenuLevOne);
	        }
	        
			JSONObject JOModule = module.tree();
			JOModule.put("nodes", JAMenuLevOne);
			JAModule.add(JOModule);
		}

        return R.ok(JAModule);
	}
}
